//
// Copyright 2022 The Sparrow Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#ifndef SPARROW_FS_H_
#define SPARROW_FS_H_

#include <string>

#include "sparrow/impl/file.h"

namespace sparrow {
namespace fs {
constexpr int READ_ONLY = FS_READ_ONLY;
constexpr int WRITE_ONLY = FS_WRITE_ONLY;
constexpr int READ_WRITE = FS_READ_WRITE;
constexpr int CREATE = FS_CREATE;
constexpr int TRUNCATE = FS_TRUNCATE;
constexpr int OPEN_EXISTING = FS_OPEN_EXISTING;
}; // namespace fs

// ------------------------
// Base class for file operations
class BaseFile final {

public:
    BaseFile();
    ~BaseFile();

    bool Init(const std::string &name);

    /**
     * @brief create or open a file
     * @param name file path
     * @param option create or open flags
     * @param share_read open or create as shared read mode
     *
     */
    bool Init(const std::string &name, int option, bool share_read);

    inline bool IsValid() const { return IsValidFileHandle(fd_); }

    int32_t Read(void *buff, int32_t size);
    int32_t Read(void *buff, int32_t size, int64_t offset);
    int32_t Write(const void *buff, int32_t size);
    int32_t Write(const void *buff, int32_t size, int64_t offset);

    int64_t GetPosition();
    bool SetPosition(int64_t offset, api::where where);

    bool Reserve(int64_t length);

    /* Close the file if it is opened */
    void Reset();

private:
    api::Handle fd_;
};
} // namespace sparrow

#endif // SPARROW_FS_H_
